package netty.CustomizeTheMessageProtocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author Kagome
 * @title: SocketClientHandler
 * @projectName boot2.X-netty
 * @description: TODO
 * @date 2019/6/4 13:26
 */
public class SocketClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
/*        UnpooledByteBufAllocator allocator = new UnpooledByteBufAllocator(false);
        ByteBuf buffer = allocator.buffer(20);
        buffer.writeInt(8);
        buffer.writeBytes("head".getBytes());
        buffer.writeBytes("body".getBytes());

        ctx.writeAndFlush(buffer);*/

//        拆包试验
//        先调整一下SocketClientHandler类中的channelActive方法中的代码,将body扩大几十倍,逼迫TCP发几次请求到达服务端,看看服务端的SelfDefineEncodeHandler能否正常处理。
//        使用一个for循环,将消息body的长度设置为1600,加上长度为4的head,总共消息长度为1604。
       /* UnpooledByteBufAllocator allocator = new UnpooledByteBufAllocator(false);
        ByteBuf buffer = allocator.buffer(20);
        buffer.writeInt(1604);
        buffer.writeBytes("head".getBytes());
        String longMsgBody = "";
        for (int i = 0; i < 400; i++) {
            longMsgBody = longMsgBody + "body";
        }
        buffer.writeBytes(longMsgBody.getBytes());

        ctx.writeAndFlush(buffer);*/
        //粘包实验
        for (int i = 0; i < 20; i++) {
            UnpooledByteBufAllocator allocator = new UnpooledByteBufAllocator(false);
            ByteBuf buffer = allocator.buffer(20);
            buffer.writeInt(8);
            buffer.writeBytes("head".getBytes());
            buffer.writeBytes("body".getBytes());

            ctx.writeAndFlush(buffer);
        }
    }
}
